package com.tangtang.project.spring;

import com.tangtang.project.spring.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Arrays;
import java.util.Map;

public class Test {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/beans.xml");
        User user = (User) applicationContext.getBean("user");
        System.out.println(user.getName());
        System.out.println(user.getAge());


        BeanFactory beanFactory = new ClassPathXmlApplicationContext("/beans.xml");
        lookupRealtime(beanFactory);
        lookupRealtimeByType(beanFactory);
        lookupCollectionByType(beanFactory);

//        AbstractXmlApplicationContext
        // org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(org.springframework.beans.factory.support.DefaultListableBeanFactory)

    }

    /**
     *
     * @param beanFactory
     */
    private static void lookupRealtime(BeanFactory beanFactory) {
        User user = (User) beanFactory.getBean("user");
        System.out.println(user);
    }

    /**
     * 根据类型查找单个bean
     * @param beanFactory
     */
    private static void lookupRealtimeByType(BeanFactory beanFactory) {
        User user =  beanFactory.getBean(User.class);
        System.out.println(user);
    }


    private static void lookupCollectionByType(BeanFactory beanFactory) {
        if(beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String,User> users =listableBeanFactory.getBeansOfType(User.class);
            System.out.println(users);

            String[] beanNamesForType = listableBeanFactory.getBeanNamesForType(User.class, true, true);
            System.out.println("getBeanNamesForType:"+Arrays.toString(beanNamesForType));

        }
    }
}
